package com.qf.hello;

import com.qf.util.RabbitMQUtil;
import com.rabbitmq.client.*;
import org.junit.Test;

import java.io.IOException;

/**
 * @author zjw
 * @description Hello World模式的消费者
 * @date 2021/11/8 15:47
 */
public class Consumer {

    @Test
    public void consume() throws Exception {
        //1. 创建连接对象
        Connection connection = RabbitMQUtil.getConnection();

        //2. 构建Channel
        Channel channel = connection.createChannel();

        //3. 构建队列
        //3.1 queue：队列名称
        //3.2 durable：队列是否持久化
        //3.3 exclusive：队列是否排外，只允许当前Connection连接
        //3.4 autoDelete：队列长时间不用，自动删除
        //3.5 args：队列其他属性，详情见图形化界面
        channel.queueDeclare("hello_queue",true,false,false,null);

        //4. 监听队列
        DefaultConsumer callback = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者获取到消息：" + new String(body));
            }
        };
        channel.basicConsume("hello_queue",true,callback);
        System.out.println("开始监听队列");

        //5. System.in.read();
        System.in.read();

        //6. 释放资源
        channel.close();
        connection.close();
    }


}
